import {defineStore} from 'pinia'
import type {IUserInfo} from '@/@types/authority'
import type {ILoginInfo} from '@/api/authority'
import {reactive,ref,computed} from 'vue'
import {getLoginApi,getUserInfoApi} from '@/api/authority'
import {useRouter} from 'vue-router'
import ls from 'store'
// 从本地存储获取用户信息
const useAuthorityStore=defineStore('authority',()=>{
const authorityInfo=ref<IUserInfo>(ls.get('authority')||{
  userid: '',
  username:'',
  nickname: '',
})
const router=useRouter()
// 从本地获取token
const token=ref<string>(ls.get('token')||'')
// 利用username来定义一个计算属性,判断是否登录
const isLoggined = computed<boolean>(() => !!authorityInfo.value.userid)


// 发送登录请求
const getLoginAction=async (params:ILoginInfo)=>{
  try {
    const data = await getLoginApi(params)
    token.value = data.token
    const info = await getUserInfoApi(data.userid)
    authorityInfo.value = info[0]
    // 进行本地存储 token, userinfo
    ls.set('token', data.token)
    ls.set('userinfo', authorityInfo.value)
    return true
  } catch (error) {}
}

const quitAction = () => {
  ls.remove('token')
  ls.remove('userinfo')
  router.replace({ name: 'main' })
}
return{
  authorityInfo,
  token,
  isLoggined,
  getLoginAction,
  quitAction
}
})
export default useAuthorityStore